package com.tuo.lf.smartfloatinghelper;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;

import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions;
import java.nio.ByteBuffer;
//import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

public class FloatingWindowService extends Service {
    private WindowManager windowManager;
    private View floatingView;
    private MediaProjectionManager mediaProjectionManager;
    private MediaProjection mediaProjection;
    private ImageReader imageReader;
    private VirtualDisplay virtualDisplay;
    private TextRecognizer textRecognizer;
    private int resultCode;
    private Intent resultData;
    private int initialX;
    private int initialY;
    private float initialTouchX;
    private float initialTouchY;
    private static final String CHANNEL_ID = "MediaProjectionChannel";
    private static final int NOTIFICATION_ID = 1;
    private Boolean ifFromMain;
    // 提取 MediaProjection.Callback 为成员变量
    private MediaProjection.Callback mediaProjectionCallback = new MediaProjection.Callback() {
        @Override
        public void onStop() {
            super.onStop();
            if (virtualDisplay != null) {
                virtualDisplay.release();
                virtualDisplay = null;
            }
            if (mediaProjection != null) {
                mediaProjection.unregisterCallback(this);
                mediaProjection.stop();
                mediaProjection = null;
            }
            if (imageReader != null) {
                imageReader.close();
                imageReader = null;
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("ForegroundServiceType")
    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
        ifFromMain=true;
//        startForeground(NOTIFICATION_ID, createNotification());
        Notification notification = createNotification();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 启动前台服务并指定类型
            startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
        } else {
            // 旧版本启动方式
            startForeground(1, notification);
        }
        floatingView = LayoutInflater.from(this).inflate(R.layout.floating_window, null);

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );

        params.gravity = Gravity.TOP | Gravity.START;
        params.x = 0;
        params.y = 100;

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        windowManager.addView(floatingView, params);

        ImageView floatingIcon = floatingView.findViewById(R.id.floating_icon);
//        floatingIcon.setOnTouchListener(new View.OnTouchListener() {
//
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                // 添加日志
//                android.util.Log.d("FloatingWindow", "悬浮窗按钮被按下");
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        initialX = params.x;
//                        initialY = params.y;
//                        initialTouchX = event.getRawX();
//                        initialTouchY = event.getRawY();
//                        // 添加日志
//                        android.util.Log.d("FloatingWindow", "ACTION_DOWN");
//                        return true;
//                    case MotionEvent.ACTION_UP:
//                        return true;
//                    case MotionEvent.ACTION_MOVE:
//                        params.x = initialX + (int) (event.getRawX() - initialTouchX);
//                        params.y = initialY + (int) (event.getRawY() - initialTouchY);
//                        windowManager.updateViewLayout(floatingView, params);
//                        return true;
//                }
//                return false;
//            }
//        });
        // 在 floatingIcon 的点击事件中调用 performOCRAndCallAPI 方法
        floatingIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 添加日志
                android.util.Log.d("FloatingWindow", "点击悬浮按钮");
                // 添加日志
                android.util.Log.d("FloatingWindow", "resultCode");
                android.util.Log.d("FloatingWindow", String.valueOf(resultCode));
                android.util.Log.d("FloatingWindow", "resultData");
                android.util.Log.d("FloatingWindow", String.valueOf(resultData));
                // 请求新的屏幕录制权限
//                Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
//                captureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(captureIntent);
                // 释放之前的资源
                if (virtualDisplay != null) {
                    virtualDisplay.release();
                    virtualDisplay = null;
                }
                if (imageReader != null) {
                    imageReader.close();
                    imageReader = null;
                }
                startScreenCapture();
//                performOCRAndCallAPI();
            }
        });

        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        textRecognizer = TextRecognition.getClient(new ChineseTextRecognizerOptions.Builder().build());

    }

//    // 在 FloatingWindowService 类中添加以下方法
//    private void performOCRAndCallAPI() {
//        // 这里简单模拟文字识别结果
//        String ocrResult = "模拟识别的文字";
//        // 添加日志
//        android.util.Log.d("FloatingWindow", "模拟识别的文字");
//        Toast.makeText(this, ocrResult, Toast.LENGTH_SHORT).show();
//        new CallAPITask().execute(ocrResult);
//    }

    private class CallAPITask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                String inputText = params[0];
                Uri.Builder builder = new Uri.Builder();
                builder.scheme("https")
                        .authority("text.pollinations.ai")
                        .appendPath("openai")
                        .appendQueryParameter("text", inputText);
                URL url = new URL(builder.build().toString());
//                URL url = new URL("https://text.pollinations.ai/openai/%E4%B8%96%E7%95%8C%E4%B8%8A%E6%9C%80%E9%AB%98%E7%9A%84%E5%B1%B1%E5%B3%B0");
//                URL url = new URL("https://text.pollinations.ai/openai?text=" + inputText);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");

                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                return response.toString();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                // 这里可以添加显示大模型返回数据的逻辑
                Toast.makeText(FloatingWindowService.this, result, Toast.LENGTH_LONG).show();
                // 添加日志
                android.util.Log.d("FloatingWindow", "result");
                android.util.Log.d("FloatingWindow", result);
            }
        }
    }

    private void startScreenCapture() {
        // 释放旧的资源
        if (virtualDisplay != null) {
            virtualDisplay.release();
            virtualDisplay = null;
        }
        if (mediaProjection != null) {
            mediaProjection.unregisterCallback(mediaProjectionCallback);
            mediaProjection.stop();
            mediaProjection = null;
        }
        if (imageReader != null) {
            imageReader.close();
            imageReader = null;
        }

        // 新增权限有效性检查
        if (!ifFromMain) {
            ifFromMain=true;
            requestNewPermission();
            return;
        }
        if (ifFromMain) {
            ifFromMain=false;
        }
        // 移除原有的resultData重用逻辑
        if (resultCode == RESULT_OK && resultData != null) {
            // mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);
            // if (mediaProjection != null) {
                // 完全释放旧实例
                if (mediaProjection != null) {
                    mediaProjection.unregisterCallback(mediaProjectionCallback);
                    mediaProjection.stop();
                    mediaProjection = null;
                }
                
                mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);
                 // 确保注册回调在创建virtualDisplay之前
                if (mediaProjection != null) {
                    mediaProjection.registerCallback(mediaProjectionCallback, new Handler(Looper.getMainLooper()));
                }

                int width = getResources().getDisplayMetrics().widthPixels;
                int height = getResources().getDisplayMetrics().heightPixels;
                imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);

                virtualDisplay = mediaProjection.createVirtualDisplay("ScreenCapture", width, height,
                        getResources().getDisplayMetrics().densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                        imageReader.getSurface(), null, null);

                imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                    @Override
                    public void onImageAvailable(ImageReader reader) {
                        Image image = reader.acquireLatestImage();
                        if (image != null) {
                            Bitmap bitmap = convertImageToBitmap(image);
                            image.close();
                            // 释放 virtualDisplay
                            if (virtualDisplay != null) {
                                virtualDisplay.release();
                                virtualDisplay = null;
                            }
                            recognizeText(bitmap);
                        }
                    }
                }, new Handler(Looper.getMainLooper()));
            // }
        }
    }
//    private void startScreenCapture() {
//        // 在创建新的 virtualDisplay 之前，释放旧的资源
//        if (virtualDisplay != null) {
//            virtualDisplay.release();
//            virtualDisplay = null;
//        }
//        if (mediaProjection != null) {
//            mediaProjection.stop();
//            mediaProjection = null;
//        }
//        // 这里需要在 MainActivity 中请求屏幕录制权限，并传递结果到这里
//        if (resultCode == RESULT_OK && resultData != null) {
//            if (mediaProjection == null) {
//                mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);
//                if (mediaProjection != null) {
//                    // 添加 MediaProjection.Callback 回调
//                    mediaProjection.registerCallback(new MediaProjection.Callback() {
//                        @Override
//                        public void onStop() {
//                            super.onStop();
//                            // 处理 MediaProjection 停止的逻辑
//                            if (virtualDisplay != null) {
//                                virtualDisplay.release();
//                                virtualDisplay = null;
//                            }
//                            if (mediaProjection != null) {
//                                mediaProjection.unregisterCallback(this);
//                                mediaProjection.stop();
//                                mediaProjection = null;
//                            }
//                            if (imageReader != null) {
//                                imageReader.close();
//                                imageReader = null;
//                            }
//                        }
//                    }, null);
//                }
//            }
//
////            // 检查 virtualDisplay 是否已经存在，如果存在则先释放它
//            if (virtualDisplay != null) {
//                virtualDisplay.release();
//                virtualDisplay = null;
//            }
//
//            int width = getResources().getDisplayMetrics().widthPixels;
//            int height = getResources().getDisplayMetrics().heightPixels;
//            if (imageReader != null) {
//                imageReader.close();
//            }
//            imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);
//
//            if (mediaProjection != null) {
//                virtualDisplay = mediaProjection.createVirtualDisplay("ScreenCapture", width, height,
//                        getResources().getDisplayMetrics().densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
//                        imageReader.getSurface(), null, null);
//            }
//
//            imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
//                @Override
//                public void onImageAvailable(ImageReader reader) {
//                    Image image = reader.acquireLatestImage();
//                    if (image != null) {
//                        Bitmap bitmap = convertImageToBitmap(image);
//                        image.close();
//                        // 添加空值检查
//                        if (virtualDisplay != null) {
//                            virtualDisplay.release();
//                        }
//                        recognizeText(bitmap);
//                        // 调用文字识别方法
////                        performRealOCR(bitmap);
//                        // 释放 virtualDisplay
//                        if (virtualDisplay != null) {
//                            virtualDisplay.release();
//                            virtualDisplay = null;
//                        }
//                    }
//                }
//            }, new Handler(Looper.getMainLooper()));
//        }
//    }

    private Bitmap convertImageToBitmap(Image image) {
        Image.Plane[] planes = image.getPlanes();
        ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * image.getWidth();

        Bitmap bitmap = Bitmap.createBitmap(image.getWidth() + rowPadding / pixelStride, image.getHeight(), Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        image.close();
        return bitmap;
    }

    private void recognizeText(Bitmap bitmap) {
        InputImage inputImage = InputImage.fromBitmap(bitmap, 0);
        textRecognizer.process(inputImage)
                .addOnSuccessListener(new OnSuccessListener<Text>() {
                    @Override
                    public void onSuccess(Text text) {
                        String resultText = text.getText();
                        if (!resultText.isEmpty()) {
                            new CallAPITask().execute(resultText);
                            android.util.Log.d("FloatingWindow", resultText);
                            Toast.makeText(FloatingWindowService.this, resultText, Toast.LENGTH_LONG).show();
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(FloatingWindowService.this, "识别失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            resultCode = intent.getIntExtra("resultCode", 0);
            resultData = intent.getParcelableExtra("resultData");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private String createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "floating_window_service_channel";
            String channelName = "悬浮窗服务通知";
            NotificationChannel channel = new NotificationChannel(
                    channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
            return channelId;
        } else {
            return null;
        }
    }

    private Notification createNotification() {
        String channelId;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = createNotificationChannel();
        } else {
            // 旧版本的渠道 ID
            channelId = "default";
        }

        Notification.Builder builder = new Notification.Builder(this, channelId);
        builder.setContentTitle("悬浮窗服务")
                .setContentText("正在运行...")
                .setSmallIcon(R.drawable.ic_notification);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFAULT);
        }

        return builder.build();
    }

    private void requestNewPermission() {
        Intent intent = new Intent(this, TransparentActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaProjection != null) {
            mediaProjection.stop();
        }
        if (textRecognizer != null) {
            textRecognizer.close();
        }
        if (floatingView != null) windowManager.removeView(floatingView);
    }
}